<?php
namespace app\components;
use app\models\Error;
use yii\web\NotFoundHttpException;

class Fun {  //extends CWidget {

 const ERROR_info = 1;
    const ERROR_SHOW=2;
    /**
     * 不记录错误
    */
   const ERROR_no=3;
    public static function showmsg($text, $type = 0) {
      
        if(is_array($text)){
            $str='';
            foreach ($text as $vo){
                $str.=$vo[0];
            }
            $text=$str;
        }
       
        
        
       
        if (defined('YII_DEBUG') && YII_DEBUG)
            { 
               throw new NotFoundHttpException($text);
            }
        
        if($type===Fun::ERROR_SHOW){
              throw new NotFoundHttpException($text);
        }
           //    Error::adderrormsg($text);   
          throw new NotFoundHttpException($text);
                        
    }
    
    
    /**
     * 返回数组类的错误信息
    */
    public static function getErrorArrayStr($array){
     ///   print_r($array);exit;
        
        $str='';
        foreach ($array as $key=> $vo){
         ///   
            foreach ($vo as $v){
                $str.=$v;   
            }
            
        }
        return $str;
    }






 

    /**
     * Curl版本
     * 使用方法：
     * $post_string = "app=request&version=beta";
     * request_by_curl('http://facebook.cn/restServer.php',$post_string);
     */
    public static function request_by_curl($remote_server, $post_string) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "");
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
 

    public static function curl_get($url) {
       /// echo "ff\r\n";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_NOSIGNAL,1);    //注意，毫秒超时一定要设置这个  
        curl_setopt($ch, CURLOPT_TIMEOUT_MS,5000);  //超时毫秒，cURL 7.16.2中被加入。从PHP 5.2.3起可使用  
       
        // echo "ff116\r\n";
        $data = curl_exec($ch);
       //  echo "118\r\n";
        
        curl_close($ch);
        return $data;
    }

    public static function date($time = 0) {
        if ($time === 0)
            return '';
        return date("Y-m-d H:i:s", $time);
    }
    public static function date_d($time = 0) {
        if ($time === 0)
            return '';
        return date("Y-m-d", $time);
    }
    /**
     * 截取字符串
    */
    public static function substr_cut($str_cut, $length) {
        if (mb_strlen($str_cut, 'utf-8') > $length) {

            $str_cut = mb_substr($str_cut, 0, $length, 'utf-8') . '…'; //截取头5个字，假定此代码所在php文件的编码为utf-8 
        }

        return $str_cut;
    }
    
     /**
     * 截取文件名字符串,并加上mp3后缀名 
    */
    public static function mp3name_cut($str_cut, $length) {
        if (mb_strlen($str_cut, 'utf-8') > $length) {

            $str_cut = mb_substr($str_cut, 0, $length, 'utf-8') . '….mp3'; //截取头5个字，假定此代码所在php文件的编码为utf-8 
        }

        return $str_cut;
    }

    public static function trimall($str) {//删除空格
        $qian = array(" ", "　", "\t", "\n", "\r");
        $hou = array("", "", "", "", "");
        return str_replace($qian, $hou, $str);
    }

    public static function en($str) {
        return urlencode($str);
    }

    /**
     * 判断是否为手机版
    */
    public static function isMobile() {
     // if(Fun::isDebug()){         return true;        }
        $mobilebrowser_list = array('iphone', 'android', 'phone', 'mobile', 'wap', 'netfront', 'java', 'opera mobi', 'opera mini',
            'ucweb', 'windows ce', 'symbian', 'series', 'webos', 'sony', 'blackberry', 'dopod', 'nokia', 'samsung',
            'palmsource', 'xda', 'pieplus', 'meizu', 'midp', 'cldc', 'motorola', 'foma', 'docomo', 'up.browser',
            'up.link', 'blazer', 'helio', 'hosin', 'huawei', 'novarra', 'coolpad', 'webos', 'techfaith', 'palmsource',
            'alcatel', 'amoi', 'ktouch', 'nexian', 'ericsson', 'philips', 'sagem', 'wellcom', 'bunjalloo', 'maui', 'smartphone',
            'iemobile', 'spice', 'bird', 'zte-', 'longcos', 'pantech', 'gionee', 'portalmmm', 'jig browser', 'hiptop',
            'benq', 'haier', '^lct', '320x320', '240x320', '176x220', 'pad', 'gt-p1000');
        if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
        $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if ((self::dstrpos($useragent, $mobilebrowser_list))) {
            return true;
        }
                        
       if ((defined('YII_DEBUG') && YII_DEBUG)&&isset($_SESSION['shouji']) && $_SESSION['shouji'] == 'true')
            return true;
                        
/*
        if (isset($_GET['moblic']) && $_GET['moblic'] == 'true')
            return true;*/
        return false;
    }

    public static function dstrpos($string, &$arr) {
        if (empty($string))
            return false;
        foreach ((array) $arr as $v) {
            if (strpos($string, $v) !== false) {
                return $v;
            }
        }
        return false;
    }
    
    /**
     * 获取ip地址
    */
       public static  function RemoteIp()
        {
              if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) 
                $ip = getenv("HTTP_CLIENT_IP"); 
                else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) 
                $ip = getenv("HTTP_X_FORWARDED_FOR"); 
                else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) 
                $ip = getenv("REMOTE_ADDR"); 
                else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) 
                $ip = $_SERVER['REMOTE_ADDR']; 
                else 
                $ip = ""; 
                
                if(empty($ip)) return  Yii::$app->request->userIP;  
                        
                $albumlist=explode(",",$ip);
              return $albumlist[0];
      }

      
      
      /**
       * 返回字符串的字数
      */
     static public function strlen($str_cut){
         return mb_strlen($str_cut, 'utf-8');
     }
      
      
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
      
   
                        
   
   /**
    * 检查手机号码是否正确,正确返回true,错误返回false
   */
   public static function isPhone($phone) {
        if ($phone == '') {
            return false;
        }
        if (!is_numeric($phone)) {
            return false;
        }
        if (strlen($phone) != 11) {
            return false;
        }
        return true;
    }
    /**
     * 判断是否为邮箱
    */
    public static function isEmail($inAddress)   
    {   
       return filter_var($inAddress, FILTER_VALIDATE_EMAIL); 
    }  
    
    
    /**
     * 判断是否为链接
    */
    public static function isHref($href){
        if(stristr($href,'http://')){
            return true;
        }else{
            return false;
        }
    }

    
    /**
     * 不判断调试开关,
     * 如果为本地调试,返回true,否则返回false
    */
   public static function isLocalDebug(){
       return Fun::RemoteIp()=='127.0.0.1';
   }


    /**
     * 一般在js,css后面,用于防止缓存,关闭调试后失效
    */
    public static function debug(){
        if(defined('YII_DEBUG')&&YII_DEBUG){
            if(Fun::RemoteIp()=='127.0.0.1'){
                return false;
            } 
            
            echo '?t='.time();
        }
    }
    /**
     * 是否为调试模式  如果为调试模式,返回true
    */
    public static function isDebug(){
        return defined('YII_DEBUG')&&YII_DEBUG;
    }

        /**
     * 临时调试成员
     */
    public static function echoDebug($t){
       if(defined('YII_DEBUG')&&YII_DEBUG){ 
           var_dump($t);echo "\r\n";
       }
    }





    public static function saveImg($base64_url){
        //文件保存目录路径
        $save_path = WEBMAIN . '/public/Uploads/';
        //文件保存目录URL
        $save_url = '/public/Uploads/';
        //检查目录
        if (@is_dir($save_path) === false) {
            self::alert("上传目录不存在。");
        }
        //检查目录写权限
        if (@is_writable($save_path) === false) {
            self::alert("上传目录没有写权限。");
        }
        $dir_name = 'image';

        $save_path .= $dir_name . "/";
        $save_url .= $dir_name . "/";
        if (!file_exists($save_path)) { 
            mkdir($save_path);
        }
          $ymd = date("Ymd");
                $save_path .= $ymd . "/";
                $save_url .= $ymd . "/";
                if (!file_exists($save_path)) {
                        mkdir($save_path);
                }
                //新文件名
                $new_file_name = date("YmdHis") . '_' . rand(10000, 99999).'.png';
                        
        $base64_body = substr(strstr($base64_url,','),1);
            $data= base64_decode($base64_body ); 
        file_put_contents($save_path.$new_file_name, $data);
        return $save_url.$new_file_name;
    }
    

   /**
     * 返回格式化时间
    */
    public static function formatTime($time){
       /// return Fun::date($time);
        
        $ca=time()-$time;
     
        if($ca<86400&&$ca>=0){   ////60*60*24 = 86400
            
            if($ca<60){
                if($ca==0){
                    return '刚刚';
                }
                  return $ca.'秒前';
              }
              $i=(int)($ca/60);
              if($i<60){
                  return $i.'分钟前';
              }
              $h=(int)($i/60);
              if($h<24){
                  return $h.'小时前';///.($i%60).'分钟前'.$ca%60;
              }
        }
        return date("n-d H:i", $time);
    }


    /**
     * 生成一个唯一字符串
    */
    public static function uniqid($uid=''){
        return md5(uniqid(microtime(true),true).$uid);
    }

    public static function strtoArray($str){
        if($str==null||$str==''){
            return [];
        }
        return explode(",",$str);
    }


    
      /**
     * 转换图片链接
     */
    public static function pImg($src)
    {
        if (empty($src)) {
            return self::$HOST . self::$Pic;
        }
        if ($src[0] === '/') {
            $src = self::$HOST . $src;
        }
        return $src;
    }
        /**@var
     * 网站域名
     */
    public static $HOST = 'http://test.fuzhuangchangongxiao.cn';  //'http://www.fuzhuangchangongxiao.cn';

    /**
     * 网站默认图片
     */
    public static $Pic = '/h5/images/logo-di.png';
}
